<?php

namespace Danmu;

require 'vendor/autoload.php';


use Danmu\Traits\SendTrait;
use Danmu\qiniu;

class WsServer
{
    use SendTrait;

    // 客户端对象
    public $clients = [];
    // websocket
    public $ws;

    public function __construct()
    {
        echo 'websocket server start...' . PHP_EOL;

        //创建websocket服务器对象，监听0.0.0.0:9502端口
        $this->ws = new \Swoole\WebSocket\Server("0.0.0.0", 9502);


        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $request) {

            $this->clients[$request->fd]['ping'] = 0;

//            print_r($request->fd, $request->get, $request->server);

            // ping 客户端，无响应则主动断开连接
            \Swoole\Coroutine::create(function () use ($request) {
                $this->clients[$request->fd]['timer_id'] = \Swoole\Timer::tick(5000, $this->ping($request));
            });
        });


        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
//            echo "Message: {$frame->data}\n";
            $data = json_decode($frame->data, true);
            switch ($data['type']) {
                case 'text':
                    $this->sendAll($frame->fd, $data['data']);
                    break;
                case 'pong':
                    $this->clients[$frame->fd]['ping'] -= 1;
                    break;
                case 'uploadToken':
                    $qiniu = new qiniu();
                    $token = $qiniu->getToken();
                    $this->sendOne($frame->fd, $token, 'token');
                    break;
                case 'record':
                case 'image':
                    $this->sendAll($frame->fd, $data['data'], $data['type']);
                    break;
            }
        });


        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            echo "client-{$fd} is closed\n";
        });

        $this->ws->start();
    }

}

new WsServer();

echo 'websocket server end! bye~';
